package com.vhall.component.service.chat.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vhall.component.dao.chat.QuickRepliesMapper;
import com.vhall.component.entity.chat.dto.QuickRepliesCreateDTO;
import com.vhall.component.entity.chat.dto.QuickRepliesDTO;
import com.vhall.component.entity.chat.entity.QuickRepliesEntity;
import com.vhall.component.entity.chat.enums.QuickRepliesStatusEnum;
import com.vhall.component.entity.chat.enums.QuickRepliesTypeEnum;
import com.vhall.component.entity.chat.vo.*;
import com.vhall.component.entity.page.vo.PageVO;
import com.vhall.component.entity.rbac.enums.RoleTypeEnum;
import com.vhall.component.framework.common.exception.BusinessException;
import com.vhall.component.plugin.common.exception.BizErrorCode;
import com.vhall.component.plugin.common.support.Token;
import com.vhall.component.plugin.common.support.TokenThreadLocal;
import com.vhall.component.service.chat.QuickRepliesConsoleService;
import com.vhall.component.service.chat.util.QuickRepliesUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 快捷回复表 服务实现类
 *
 * @author xing.wang
 * @since 2022-09-05
 */
@Service(value = "QuickRepliesConsole")
@Slf4j
@RequiredArgsConstructor
public class QuickRepliesConsoleServiceImpl extends ServiceImpl<QuickRepliesMapper, QuickRepliesEntity> implements QuickRepliesConsoleService {
    private final QuickRepliesUtils quickRepliesUtils;

    /**
     * 最大启用限制数量
     */
    @Value("${project.limit.quick-replies.open-num:10}")
    private Integer OPEN_COUNT_LIMIT;

    @Override
    public QuickRepliesCreateDTO create(QuickRepliesCreateVO vo) {
        Token token = TokenThreadLocal.getToken();
        if (token.getRoleType() == null || RoleTypeEnum.DEPT_LEVEL.getValue().equals(token.getRoleType())) {
            return new QuickRepliesCreateDTO();
        }
//        验证是否存在重复的快捷回复内容
        if (quickRepliesUtils.checkContentExists(vo.getContent(), 0)) {
            throw new BusinessException(BizErrorCode.COMP_QUICKREPLIES_EXIST_CONTENT_ERROR);
        }
        QuickRepliesEntity entity = new QuickRepliesEntity();
        LocalDateTime now = LocalDateTime.now();
//        admin端用户创建的快捷回复默认设置关联的account_id为0
        entity.setAccountId(token.getAccountId());
        entity.setContent(vo.getContent());
        entity.setUpdatedAt(now);
        entity.setCreatedAt(now);
        entity.setStatus(QuickRepliesStatusEnum.DISABLE.getStatus());
        entity.setType(QuickRepliesTypeEnum.CUSTOM.getType());
        save(entity);
        QuickRepliesCreateDTO quickRepliesDTO = new QuickRepliesCreateDTO();
        BeanUtil.copyProperties(entity, quickRepliesDTO, false);
        return quickRepliesDTO;
    }

    @Override
    public Boolean update(QuickRepliesUpdateVO vo) {
        Token token = TokenThreadLocal.getToken();
        if (token.getRoleType() == null || RoleTypeEnum.DEPT_LEVEL.getValue().equals(token.getRoleType())) {
            return false;
        }
        Integer repliesId = vo.getRepliesId();
//        验证是否有权限修改当前快捷回复
        checkChangeQuickRepliesAuth(repliesId, null);
//        验证是否修改后会产生重复
        if (quickRepliesUtils.checkContentExists(vo.getContent(), repliesId)) {
            throw new BusinessException(BizErrorCode.COMP_QUICKREPLIES_EXIST_CONTENT_ERROR);
        }
        QuickRepliesEntity entity = baseMapper.selectById(repliesId);
        entity.setUpdatedAt(LocalDateTime.now());
        entity.setContent(vo.getContent());
        return updateById(entity);
    }

    @Override
    public Boolean delete(QuickRepliesDeleteVO vo) {
        Token token = TokenThreadLocal.getToken();
        if (token.getRoleType() == null || RoleTypeEnum.DEPT_LEVEL.getValue().equals(token.getRoleType())) {
            return false;
        }
        Integer repliesId = vo.getRepliesId();
        checkChangeQuickRepliesAuth(repliesId, null);
        return removeById(repliesId);
    }

    /**
     * 判断当前用户是否有权限修改本条快捷回复
     * 修改的数据是否存在,修改的数据拥有人是否是当前用户
     *
     * @param repliesId 快捷回复id
     * @param accountId 用户id
     */
    private void checkChangeQuickRepliesAuth(Integer repliesId, Integer accountId) {
        QuickRepliesEntity quickRepliesEntity = baseMapper.selectById(repliesId);
        if (Objects.isNull(quickRepliesEntity)) {
            throw new BusinessException(BizErrorCode.COMP_QUICKREPLIES_EMPTY);
        }
//        if (Objects.nonNull(quickRepliesEntity.getAccountId()) && !quickRepliesEntity.getAccountId().equals(accountId)) {
//            throw new BusinessException(BizErrorCode.COMP_QUICKREPLIES_ACCOUNT_AUTH_ERROR);
//        }
    }

    @Override
    public Boolean setStatus(QuickRepliesSetStatusVO vo) {

        Token token = TokenThreadLocal.getToken();
        if (token.getRoleType() == null || RoleTypeEnum.DEPT_LEVEL.getValue().equals(token.getRoleType())) {
            return false;
        }

        Integer repliesId = vo.getRepliesId();
//        验证是否有权限修改快捷回复
        checkChangeQuickRepliesAuth(repliesId, null);
//        验证开启的快捷回复超过了预期快捷回复
        if (QuickRepliesStatusEnum.OPEN.getStatus().toString().equals(vo.getStatus())) {
            quickRepliesUtils.checkQuickRepliesOpenNum(null);
        }
        QuickRepliesEntity entity = new QuickRepliesEntity();
        entity.setUpdatedAt(LocalDateTime.now());
        entity.setId(repliesId);
        entity.setStatus(Integer.valueOf(vo.getStatus()));
        return updateById(entity);
    }

    @Override
    public PageVO<QuickRepliesDTO> pageList(QuickRepliesListVO vo) {
        Token token = TokenThreadLocal.getToken();
        if (token.getRoleType() == null || RoleTypeEnum.DEPT_LEVEL.getValue().equals(token.getRoleType())) {
            return new PageVO<>();
        }

        LambdaQueryWrapper<QuickRepliesEntity> where = Wrappers.lambdaQuery();
        where.like(StringUtils.isNotEmpty(vo.getKeyword()), QuickRepliesEntity::getContent, vo.getKeyword());
        where.isNull(QuickRepliesEntity::getDeletedAt);
        where.orderByDesc(QuickRepliesEntity::getCreatedAt);

        Integer pageIndex = vo.getPage();
        Integer pageSize = vo.getPageSize();
        return quickRepliesUtils.getQuickRepliesDTOPageVO(where, pageIndex, pageSize);
    }

    @Override
    public Boolean startStatusNum() {
        LambdaQueryWrapper<QuickRepliesEntity> where = Wrappers.lambdaQuery();
        where.eq(QuickRepliesEntity::getStatus, QuickRepliesStatusEnum.OPEN.getStatus());
        where.isNull(QuickRepliesEntity::getDeletedAt);
        int openNum = baseMapper.selectCount(where);
        return openNum < OPEN_COUNT_LIMIT;
    }

}
